// CacheWorker
package main

import (
	//"errors"
	"log"
	"os"
	"path"
)

var nextworkerid int = 0

var CacheWorkerChannel chan Cacheworkitem = make(chan Cacheworkitem, 1000)

var cacheworkers = make([]Worker, 5)

func Addcacheworker() {
	wrk := Worker{}
	wrk.id = nextworkerid
	nextworkerid++
	wrk.cmd = make(chan Workercommand)
	go cacheworker(wrk)
	cacheworkers = append(cacheworkers, wrk)
}

func cacheworker(wrk Worker) {
	log.Println("Worker", wrk.id, "started")

	for {
		select {
		case cmd := <-CacheWorkerChannel:
			log.Println("Worker", wrk.id, "Command", cmd, "received")
			item, ok := Cache[cmd.name]
			if !ok {
				item = &Cacheitem{}
				item.name = cmd.name
				item.relpath = cmd.relpath
				item.score = 1

				f, err := os.Open(path.Join(Basedir, item.relpath))
				if err != nil {
					log.Println("Worker", wrk.id, item.relpath, "is faulty")
					item.faulty = err
				} else {
					stat, _ := f.Stat()
					if stat.IsDir() {
						log.Println("Worker", wrk.id, item.relpath, "is dir; faulty")
						item.cacheable = false
					} else {
						log.Println("Worker", wrk.id, item.relpath, "is good")
						item.faulty = nil
						item.cacheable = true
					}

				}
				log.Println("Created new cache item", item.name)
				Cache[item.name] = item
			} else {
				item.score++
				log.Println("Increases cache item score", item.name)
			}

			cmd.retchan <- item
		case cmd := <-wrk.cmd:
			if cmd == WORKER_EXIT {
				log.Println("Worker", wrk.id, "exiting")
				return
			}
		}
	}
}

const (
	WORKER_EXIT Workercommand = -1
)

const (
	CACHE_FETCH       Cachecommand = 1
	CACHE_FETCH_SCORE Cachecommand = 2
)

type Workercommand int
type Cachecommand int

type Worker struct {
	id  int
	cmd chan Workercommand
}

type Cacheworkitem struct {
	name    string
	relpath string
	command Cachecommand
	retchan chan *Cacheitem
}
